<?php

namespace Library\Core;

/**
 * Class Signal
 * 信号量
 */
class Signal
{
    private static $signal;

    private static $runing = true;

    /**
     * Signal constructor.
     * @throws
     */
    private function __construct()
    {
        if (PHP_SAPI != 'cli') {
            throw new \Exception('Must CLI Model');
        }
        static::pcntl_signal();
    }

    /**
     * 安装信号处理器 kill 2
     */
    private static function pcntl_signal()
    {
        // 三参数必须为false 缺省参数存在bug --disable-posix
        pcntl_signal(SIGINT, function () {
            self::$runing = false;
        }, false);
    }

    /**
     * 调用等待信号的处理器
     * @param $runing
     * @return bool
     */
    public static function dispatch()
    {
        self::init();

        pcntl_signal_dispatch();

        return self::$runing;
    }

    /**
     * @desc 初始
     * @return mixed
     * @throws
     *------------------------------------------------------
     */
    private static function init()
    {
        if (!isset(static::$signal)) {
            static::$signal = new self();
        }

        return static::$signal;
    }

}